require('module-alias/register')
var config = require('@root/config.js')
let request = require("request");
var { sunnyCitys } = require('@Sequelize')



// 生成token
function createToken(){
    
}

var byIdGetData = function (req, res, next) {
    res.send("100000")
}
async function updataCityGeo(req, res, next){
    var data = await sunnyCitys.findAll({
        
    })
    for (let index = 0; index < data.length; index++) {
        const item = data[index];
        if (item.id.length<6){
            makeUp(item.id,"id")
        }
        if (item.parentId.length < 6) {
            makeUp(item.parentId, "parentId")
        }
        // if (!item.geoData){
        //     await insertGeoDataByID(item.id)
        // }

        if (!item.geoAllData && item.id.indexOf("00")!=-1) {
            await insertGeoAllDataByID(item.id)
        }
    }
    res.send({})
}

function makeUp(id,key) {
    console.log(id, key)
    var value=id+'000000'
    value = value.substring(0, 6);
    var where ={}
    where[key] = id
    var valueObj={}
    valueObj[key] = value
    sunnyCitys.update(valueObj, {
        where: where
    }).then(res=>{

    })
}
async function insertGeoDataByID(id) {
    await request(`https://geo.datav.aliyun.com/areas_v2/bound/${id}.json`, function (error, response, body) {
        if (!error) {
            try {
                response.body = JSON.substring(response.body)
            } catch (error) {
                response.body = ""
            }
            sunnyCitys.update({ geoData: response.body }, {
                where: { id }
            }).then(res => {
            })
        }
    })

}
async function insertGeoAllDataByID(id) {
    await request(`https://geo.datav.aliyun.com/areas_v2/bound/${id}_full.json`, function (error, response, body) {
        if (!error) {
            try {
                JSON.parse(response.body)
            } catch (er) {
                response.body = null
            }
            if (response.body){
                sunnyCitys.update({ geoAllData: response.body }, {
                    where: { id }
                }).then(res => {
                })
            }
            
        }
    })

}
var getClientID = function (req, res, next) {
    res.send({ foo: 'bar' })
}
module.exports = { byIdGetData, updataCityGeo }; 